<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :size="size"
    filterable
    :readonly="readonly"
    :multiple="multiple"
    :clearable="clearable"
    @change="handleChange"
  >
    <el-option
      v-for="item in selectOptions"
      :key="item[valuePropName]"
      :label="item[labelPropName]"
      :value="item[valuePropName]"
    >
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: 'Selector',
  data() {
    return {
      selectedValue: this.value,
      selectOptions: []
    }
  },
  watch: {
    selectedValue() {
      this.$emit('input', this.selectedValue)
    },
    value() {
      this.selectedValue = this.value
    },
    async options() {
      this.selectOptions = await this.getOptions()
    }
  },
  async created() {
    this.selectOptions = await this.getOptions()
  },
  methods: {
    async getOptions() {
      if (Array.isArray(this.options)) {
        return this.options
      }
      if (this.options instanceof Promise) {
        return await this.options
      }
      return this.options.getOptions()
    },
    handleChange(value) {
      this.$emit('change', {value, option: this.selectOptions.find(el => el.value === value)})
    }
  },
  props: {
    value: {
      type: [String, Number, Object, Array],
      default: null
    },
    options: {
      type: [Array, Object, Function, Promise],
      default() {
        return []
      }
    },
    valuePropName: {
      type: String,
      default: 'value'
    },
    size: {
      type: String,
      default: 'mini'
    },
    labelPropName: {
      type: String,
      default: 'label'
    },
    placeholder: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    }
  }
}
</script>
